package zy.controller.wx;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import zy.controller.BaseController;
import zy.controller.util.WxCommonUtil;
import zy.entity.wx.my.T_Wx_Address;
import zy.entity.wx.order.T_Wx_Order;
import zy.entity.wx.order.T_Wx_Order_Detail;
import zy.entity.wx.user.T_Wx_User;
import zy.entity.wx.user.T_Wx_User_Account_Detail;
import zy.service.wx.user.WxUserService;
import zy.util.CommonUtil;
import zy.util.MD5;
import zy.util.StringUtil;
import zy.util.WeixinUtil;


@Controller
public class WxUserController extends BaseController{
	@Autowired
	private WxUserService wxUserService;
	
	@RequestMapping(value = "login/{mobile}/{password}/{nickname}/{avatarurl}", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody Object login(@PathVariable String mobile,@PathVariable String password,@PathVariable String nickname,@PathVariable String avatarurl) {
		return ajaxSuccess(wxUserService.login(mobile, MD5.encryptMd5(password),nickname,avatarurl));
	}
	
	@RequestMapping(value = "login", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object login(@RequestBody Map<String, Object> params) {
		Map<String, Object> data = new HashMap<String, Object>();
		T_Wx_User  user= wxUserService.login(params);
		if (user != null){
			data.put("user", user);
			String wu_code = user.getWu_code();
			
			T_Wx_Address address =wxUserService.getAddress(wu_code);
			data.put("address", address);
			
		} 
		
		return ajaxSuccess(data);
		
//		Map<String, Object> data = new HashMap<String, Object>();
//		data.put("user", ajaxSuccess(wxUserService.login(params)));
//		
//		//获取地址
//		data.put("user", ajaxSuccess(wxUserService.getAddress(params)));
//		return data;
		//return ajaxSuccess(wxUserService.login(params));
	}
	
	@RequestMapping(value = "/api/wx/user/update", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object update(@RequestBody Map<String, Object> params) {
		Map<String, Object> data = new HashMap<String, Object>();
		T_Wx_User  user= wxUserService.update(params);
		data.put("user", user);
		
		return ajaxSuccess(data);
		
	}
	
	@RequestMapping(value = "register", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object register(T_Wx_User wxUser) {
		
		return ajaxSuccess(wxUserService.save(wxUser));
	}
	
	//修改密码
	@RequestMapping(value = "updatePassword/{old_password}/{new_password}/{confirm_password}", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody Object updatePassword(@PathVariable String old_password,@PathVariable String new_password,@PathVariable String confirm_password) {
		return ajaxSuccess(wxUserService.updatePassword(MD5.encryptMd5(new_password), MD5.encryptMd5(new_password), MD5.encryptMd5(confirm_password)));
	}
	
	//获取微信授权信息(靳征)
	//code 微信前端转入
    
    @RequestMapping(value="/api/wx/user/auth",method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object auth(@RequestBody Map<String, Object> params){//HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> map = new HashMap<String, Object>();
        String status = "200";
        String msg = "ok";
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        try {
            String code = StringUtil.trimString(params.get("code"));//request.getParameter("code");
            if(StringUtils.isBlank(code)){
                status = "500";//失败状态
                msg = "code为空";
            }else {
                String requestUrl = WX_URL.replace("APPID", WeixinUtil.my_app_id).
                        replace("SECRET", WeixinUtil.my_app_secret).replace("JSCODE", code);
                        //replace("authorization_code", WeixinConstants.AUTHORIZATION_CODE);
                //logger.info(requestUrl);
                // 发起GET请求获取凭证
                JSONObject jsonObject = WxCommonUtil.httpsRequest(requestUrl, "GET", null);
                
                if (jsonObject != null) {
                    try {
                    	if (StringUtil.isNotEmpty(jsonObject.getString("openid"))){
                    		//查询当前用户数据是否落地，保存更新，返回当前用户信息
                    		params.put("wu_openid", jsonObject.getString("openid"));
                    		T_Wx_User user = wxUserService.initUser(params);
                    		
                    		
                    		map.put("openid", jsonObject.getString("openid"));
                            map.put("session_key", jsonObject.getString("session_key"));
                            map.put("user", user);
                    	}
                        
                    } catch (JSONException e) {
                        // 获取token失败
                        status = "500";
                        msg = "code无效";
                    }
                }else {
                    status = "500";
                    msg = "code无效";
                }
            }
            map.put("status", status);
            map.put("msg", msg);
        } catch (Exception e) {
        	 map.put("status", 500);
             map.put("msg", e.getMessage());
            //logger.error(e.getMessage(),e);
            //return AnalyzeMoblieData.errorResponse();
        }
        return ajaxSuccess(map);

    }
    
    @RequestMapping(value="/api/wx/user/getAccountDetails",method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
	public Object getAccountDetails(@RequestBody Map<String, Object> paramMap) {

    	Object object = wxUserService.getAccoutDetails(paramMap);
		
		return returnResult(object);
	}
	
    
    @RequestMapping(value = "/api/wx/user/saveUserInfo", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object saveUserInfo(@RequestBody Map<String, Object> params) {
		Map<String, Object> data = new HashMap<String, Object>();
		T_Wx_User  user= wxUserService.saveUserInfo(params);
		data.put("user", user);
		
		return ajaxSuccess(data);
		
	}
    
   
	
}
